package com.qf.smsplatform.strategy.service.impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.service.Strategy;
import com.qf.smsplatform.strategy.service.api.CacheService;
import com.qf.smsplatform.strategy.utils.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;
import java.io.StringReader;

/**
 * @Author: LeeRui
 * 2021/1/27 下午 9:18
 * 敏感词过滤策略
 **/
@Service(value = "dirtyWord")
@Slf4j
public class DirtyWordStrategy implements Strategy {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        log.info("【敏感词过滤策略】 敏感词过滤策略开始执行！！！");

        //获取用户发送的短信内容
        String messageContent = standardSubmit.getMessageContent();

        //将短信内容使用IK分词器分词
        StringReader stringReader = new StringReader(messageContent);
        IKSegmenter ikSegmenter = new IKSegmenter(stringReader, true);

        //遍历分词器分出来的词，Redis中进行匹配
        Lexeme lexeme = null;
        while (true) {
            try {
                //若下一个目标为null，则跳出循环
                if ((lexeme = ikSegmenter.next()) == null) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取分词内容
            String text = lexeme.getLexemeText();
            //判断Redis缓存的敏感词表中是否存在改词汇
            Boolean aBoolean = cacheService.sismember(CacheConstants.CACHE_PREFIX_DIRTY_WORDS_KEY, text);
            if (aBoolean) {  //若存在，敏感词校验失败，打印日志，并向MQ指定队列发送日志和报告
                log.info("【敏感词过滤策略】 敏感词过滤策略校验失败！！！");
                //向TOPIC_SMS_SEND_LOG队列发送日志
                pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_DIRTY_WORDS);
                //向TOPIC_PUSH_SMS_REPORT队列发送报告
                pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_DIRTY_WORDS);
                return false;
            }
        }

        //敏感词校验成功，打印日志
        log.info("【敏感词过滤策略】 敏感词过滤策略校验成功！！！");
        return true;
    }
}
